{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### operator.itemgetter\n",
    "- 通过公共键对字典列表进行排序\n",
    "- 函数``operator.itemgetter()``接受的参数可作为查询的标记，用来从序列的记录中提取出所需的值，他可以是字典的键名称、用数字表示的列表元素或是任何可以传给对象的``__getitem__()``方法的值，如果传多个标记给``itemgetter()``，那它产生的可调用对象将返回一个包含所有元素在内的元组。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[{'fname': 'Brain', 'lname': 'Jones', 'uid': '1003'}, {'fname': 'David', 'lname': 'Beazley', 'uid': '1001'}, {'fname': 'David', 'lname': 'Aones', 'uid': '1002'}]\n",
      "[{'fname': 'Brain', 'lname': 'Jones', 'uid': '1003'}, {'fname': 'David', 'lname': 'Aones', 'uid': '1002'}, {'fname': 'David', 'lname': 'Beazley', 'uid': '1001'}]\n",
      "{'fname': 'David', 'lname': 'Beazley', 'uid': '1001'}\n",
      "{'fname': 'Brain', 'lname': 'Jones', 'uid': '1003'}\n"
     ]
    }
   ],
   "source": [
    "rows = [\n",
    "    {'fname': 'Brain', 'lname': 'Jones', 'uid': '1003'},\n",
    "    {'fname': 'David', 'lname': 'Beazley', 'uid': '1001'},\n",
    "    {'fname': 'David', 'lname': 'Aones', 'uid': '1002'},\n",
    "]\n",
    "\n",
    "from operator import itemgetter\n",
    "rows_by_fname = sorted(rows, key=itemgetter('fname'))\n",
    "rows_by_name = sorted(rows, key=itemgetter('fname', 'lname'))\n",
    "print(rows_by_fname)\n",
    "print(rows_by_name)\n",
    "eldest_staff = min(rows, key=itemgetter('uid'))                 # 同理可用于max或min函数\n",
    "youngest_staff = max(rows, key=itemgetter('uid'))\n",
    "print(eldest_staff)\n",
    "print(youngest_staff)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- ``lambda``表达式可以做到``itemgetter()``一样的效果，但后者通常会运行得更快一些"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[{'fname': 'Brain', 'lname': 'Jones', 'uid': '1003'}, {'fname': 'David', 'lname': 'Beazley', 'uid': '1001'}, {'fname': 'David', 'lname': 'Aones', 'uid': '1002'}]\n",
      "[{'fname': 'Brain', 'lname': 'Jones', 'uid': '1003'}, {'fname': 'David', 'lname': 'Aones', 'uid': '1002'}, {'fname': 'David', 'lname': 'Beazley', 'uid': '1001'}]\n"
     ]
    }
   ],
   "source": [
    "rows_by_fname = sorted(rows, key=lambda r: r['fname'])\n",
    "rows_by_lname = sorted(rows, key=lambda r: (r['fname'], r['lname']))\n",
    "print(rows_by_fname)\n",
    "print(rows_by_name)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### operator.attrgetter\n",
    "- 通过公共属性对对象列表进行排序\n",
    "- 同``operator.itemgetter``相似，要求对象具有`.`获取属性的方法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[User(1), User(2), User(4)]\n",
      "[User(1), User(4), User(2)]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "User(2)"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "class User:\n",
    "    def __init__(self, user_id, age):\n",
    "        self.user_id = user_id\n",
    "        self.age = age\n",
    "    def __repr__(self):\n",
    "        return 'User({0})'.format(self.user_id)\n",
    "\n",
    "user_list = [User(1, 10), User(2, 20), User(4, 10)]\n",
    "\n",
    "from operator import attrgetter\n",
    "print(sorted(user_list, key=attrgetter('user_id')))\n",
    "print(sorted(user_list, key=attrgetter('age', 'user_id')))\n",
    "max(user_list, key=attrgetter('age'))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3.7.4 64-bit",
   "language": "python",
   "name": "python37464bit0eab7a6caf29454899b876d50238c56e"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
